import * as Location from "expo-location";

// 地图这个权限有问题：使用google地图不现实，使用webview替换这个方案
import { Alert, Button, StyleSheet, Text, View } from "react-native";
import React, { useEffect, useState } from "react";

const TabTwoScreen = () => {
  const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);
  const [hasPermission, setHasPermission] = useState(null);

  const DEFAULT_LOCATION = {
    coords: {
      latitude: 37.7749,
      longitude: -122.4194,
    },
    timestamp: Date.now(),
  };

  useEffect(() => {
    (async () => {
      const { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== "granted") {
        setErrorMsg("Permission to access location was denied");
        setHasPermission(false);
        return;
      }
      setHasPermission(true);

      const servicesEnabled = await Location.hasServicesEnabledAsync();
      if (!servicesEnabled) {
        setErrorMsg("Location services are disabled");
        return;
      }

      try {
        const location = await getLocationWithTimeout();
        setLocation(location);
      } catch (error) {
        setErrorMsg("Error while getting location: " + error.message);
        setLocation(DEFAULT_LOCATION);
      }
    })();
  }, []);

  const getLocationWithTimeout = async (timeout = 10000) => {
    return new Promise((resolve, reject) => {
      const timer = setTimeout(() => {
        reject(new Error("Location request timed out"));
      }, timeout);

      Location.getCurrentPositionAsync({})
        .then((location) => {
          clearTimeout(timer);
          resolve(location);
        })
        .catch((error) => {
          clearTimeout(timer);
          reject(error);
        });
    });
  };

  const getLocation = async () => {
    const { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== "granted") {
      setErrorMsg("Permission to access location was denied");
      setHasPermission(false);
      return;
    }
    setHasPermission(true);

    const servicesEnabled = await Location.hasServicesEnabledAsync();
    if (!servicesEnabled) {
      setErrorMsg("Location services are disabled");
      Alert.alert(
        "Location Services Disabled",
        "Please enable location services to use this feature.",
        [{ text: "OK" }]
      );
      return;
    }

    try {
      const location = await getLocationWithTimeout();
      setLocation(location);
    } catch (error) {
      setLocation(DEFAULT_LOCATION);
      setErrorMsg("Error while getting location: " + error.message);
    }
  };

  let text = "Waiting..---app.json没有配置google密钥，有机会换一个";
  if (errorMsg) {
    text = errorMsg;
  } else if (location) {
    text = `Location: Latitude ${location.coords.latitude}, Longitude ${location.coords.longitude}`;
  }

  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>{text}</Text>
      <Button title="Get Location" onPress={getLocation} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  paragraph: {
    fontSize: 18,
    textAlign: "center",
    margin: 10,
  },
});

export default TabTwoScreen;
